package com.wgj.android.ui.activity;

import android.animation.Animator;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.jiaai.xui.adapter.XRecyclerViewAdapter;
import com.jiaai.xui.adapter.XViewHolder;
import com.jiaai.xui.adapter.decoration.DividerDecoration;
import com.jiaai.xui.imagepicker.Utils.GridSpacingItemDecoration;
import com.jiaai.xui.utils.XAppUtils;
import com.jiaai.xui.utils.XDateUtils;
import com.jiaai.xui.utils.XDensityUtils;
import com.jiaai.xui.view.widget.XAlertMsgDialog;
import com.jiaai.xui.view.widget.XToast;
import com.wgj.android.R;
import com.wgj.android.accesslibility.config.WXConfginUtil;
import com.wgj.android.dialog.CleanFriednsConfigDialog;
import com.wgj.android.http.WeiXinEvents;
import com.wgj.android.http.weixin.WXHttp;
import com.wgj.android.http.weixin.WeiXinCacheUtil;
import com.wgj.android.http.weixin.event.CleanEvent;
import com.wgj.android.http.weixin.model.CleanInfo;
import com.wgj.android.utils.CacheUtils;
import com.wgj.android.utils.MD5Util;
import com.wgj.android.zfp.CleanFirendsTaskManager;
import com.wgj.android.zfp.WXCleanService;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindInt;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2017/11/29.
 */

public class CleanFriednsActivity extends AppCompatActivity {
    private  static  int disposeNum=0;
    @BindView(R.id.time3)
    Chronometer time3;
    @BindView(R.id.a1)
    ImageView a1;
    @BindView(R.id.startCleanBut)
    Button startCleanBut;



    @BindView(R.id.listView)
    RecyclerView listView;

    @BindView(R.id.animIcon)
    ImageView animIcon;

    @BindView(R.id.msgText)
    TextView msgText;

    @BindView(R.id.msgContentView)
    View msgContentView;

    @BindView(R.id.time)
    View timeView;

    @BindView(R.id.timeS)
    TextView timeS;
    @BindView(R.id.cn)
    TextView cnView;

    @BindView(R.id.statusView)
    View statusView;

    @BindView(R.id.contentView)
    View contentView;

    @BindView(R.id.stopCleanBut)
    View stopCleanBut;

    @BindView(R.id.headView)
    View headView;

    @BindView(R.id.all)
    TextView tvAll;

    @BindView(R.id.del)
    TextView tvDel;
    private String basePath;
    private long startTime=0;
    private XRecyclerViewAdapter<String> adapter;
    private ArrayList<String> cleans=new ArrayList<>();
    private ArrayList<String> sussces=new ArrayList<>();
    private ArrayList<String> faileds=new ArrayList<>();
    private int totalFirdns=0;//总计清理的人数


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        int flag= WindowManager.LayoutParams.FLAG_FULLSCREEN;
        //设置当前窗体为全屏显示
        getWindow().setFlags(flag, flag);
        if(savedInstanceState!=null &&savedInstanceState.containsKey("cleans")&& !XAppUtils.isServiceRunning(WXCleanService.class.getName())){
            cleans= (ArrayList<String>) savedInstanceState.getSerializable("cleans");
            sussces= (ArrayList<String>) savedInstanceState.getSerializable("sussces");
            faileds= (ArrayList<String>) savedInstanceState.getSerializable("faileds");
            totalFirdns=savedInstanceState.getInt("totalFirdns");
            startServers();

        }


        super.setContentView(R.layout.start_clean_friends_activity);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        if (WeiXinCacheUtil.getInfo() != null){
            basePath = Environment.getExternalStorageDirectory()+"/wgj"+ File.separator+"weixing"+ File.separator+ WeiXinCacheUtil.getInfo().getWxuin()+File.separator;
        }
        if(XAppUtils.isServiceRunning(WXCleanService.class.getName())){
           onClean();
        }
        adapter=new XRecyclerViewAdapter<String>(listView,cleans,R.layout.clean_friends_item) {
            @Override
            protected void bindData(XViewHolder xViewHolder, String s, int i) {
                String path=basePath.concat(MD5Util.encrypt(s));
                Glide.with(getContext()).load(new File(path)).placeholder(R.mipmap.img_default_head).into((ImageView) xViewHolder.getView(R.id.head));
                TextView textView=xViewHolder.getView(R.id.status);
                xViewHolder.setText(R.id.nickName,s);
                if(sussces.contains(s)){
                    textView.setText("成功");
                    textView.setTextColor(Color.parseColor("#fff000"));
                }else if(faileds.contains(s)){
                    textView.setText("失败");
                    textView.setTextColor(Color.parseColor("#ff6464"));
                }else {
                    textView.setText("待处理");
                    textView.setTextColor(Color.WHITE);
                }

            }
        };

        listView.setLayoutManager(new LinearLayoutManager(this));
        listView.setHasFixedSize(true);
        listView.addItemDecoration(new DividerDecoration(Color.TRANSPARENT, XDensityUtils.dp2px(1)));
        listView.setAdapter(adapter);


    }


    @OnClick(R.id.startCleanBut)
    public  void  onStartClean(View view){
        if(WXHttp.checkIsLogin()){
            startServers();
        }else {
            WeiXinLoginActivity.openWeiXingLoginUI(getApplication());

        }
    }

    @OnClick(R.id.settingBut)
    public  void  settingConfig(View view){
        new CleanFriednsConfigDialog().show(getSupportFragmentManager(),"CleanFriednsConfigDialog");
    }
    @OnClick(R.id.backBut)
    public  void  onBackClick(View view){
         finish();
    }
    private void  startServers(){

        if(!XAppUtils.isServiceRunning(WXCleanService.class.getName())){
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    Intent intent = new Intent(CleanFriednsActivity.this, WXCleanService.class);
                    startService(intent);
                }
            },3000);

        }
        onClean();
    }
    private void  onClean(){
        if(startTime==0){
            startTime=SystemClock.elapsedRealtime();
        }
        time3.setBase(startTime);//计时器清零
        int hour = (int) ((SystemClock.elapsedRealtime() - time3.getBase()) / 1000 / 60);
        time3.setFormat("0"+String.valueOf(hour)+":%s");
        time3.start();
        startCleanBut.setVisibility(View.GONE);
        stopCleanBut.setVisibility(View.VISIBLE);
        statusView.setVisibility(View.VISIBLE);
        contentView.setVisibility(View.VISIBLE);
        headView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,XDensityUtils.dp2px(120)));
        msgText.setText("正在初始化中....");
        animIcon.startAnimation(animationRotateAnimation());
        a1.startAnimation(createRotateAnimation());
        a1.setVisibility(View.VISIBLE);


    }
    private  void  hideView(){
//        animIcon.setAnimation(null);
//        a1.setAnimation(null);
//        a1.setVisibility(View.GONE);
//        cleans.clear();
//        adapter.notifyDataSetChanged();
//        totalFirdns=0;
//        sussces.clear();
//        faileds.clear();
//        headView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,XDensityUtils.getScreenWidth()/2));
//        startCleanBut.setVisibility(View.VISIBLE);
//        stopCleanBut.setVisibility(View.GONE);
//        statusView.setVisibility(View.GONE);
//        contentView.setVisibility(View.GONE);
        Toast.makeText(this,"您的好友已全部检测完成",Toast.LENGTH_SHORT).show();
        finish();
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public   void onWeiXingLoginEvents(WeiXinEvents events){
        switch (events.getType()){
            case WeiXinEvents.EventsType.LOGIN:
                startServers();
                break;
            case  WeiXinEvents.EventsType.LOGIN_OUT:
                WeiXinLoginActivity.openWeiXingLoginUI(getApplication());
                Toast.makeText(this,"你的微信已登出,请重新扫码登录!",Toast.LENGTH_LONG);
                break;
        }


    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public   void onCleanEvents(CleanEvent event){
        int cleanSize=WeiXinCacheUtil.getCleanInfo(WeiXinCacheUtil.getInfo().getWxuin()).getNickNames().size();
        switch (event.getStatus()){
            case CleanEvent.type.LOGIND:
                 msgText.setText("正在初始化中,请稍等...");
                 break;
            case CleanEvent.type.LOGIND_END:
                 totalFirdns=Integer.valueOf(event.getNickName());
                if(totalFirdns==cleanSize && WXConfginUtil.isOpenCleanFirendFilter() ){
                    hideView();
                    return;
                }
                cnView.setText(cleanSize+"/"+(totalFirdns));
                tvAll.setText(totalFirdns+"");
                timeS.setText(secToTime(totalFirdns*3));
                break;
            case  CleanEvent.type.CHECKING:
                 disposeNum++;
                 cnView.setText((cleanSize+disposeNum)+"/"+(totalFirdns));
                 msgText.setText("正在检测"+event.getNickName());
                break;

            case CleanEvent.type.CLEAN:
                 cleans.add(0,event.getNickName());
                 tvDel.setText(cleans+"");
                 adapter.notifyDataSetChanged();
                 break;
            case CleanEvent.type.SUCCESS:
                  sussces.add(event.getNickName());
                  adapter.notifyDataSetChanged();
                 break;
            case CleanEvent.type.FAILED:
                 faileds.add(event.getNickName());
                 adapter.notifyDataSetChanged();
                break;
            case CleanEvent.type.STOP_CLEAN:
                hideView();
                XToast.success("检测完成");
                break;

        }


    }


    @OnClick(R.id.stopCleanBut)
    public  void onStopClick(View view){
        WXCleanService.stop();
        hideView();
        XToast.success("检测完成");
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        if(XAppUtils.isServiceRunning(WXCleanService.class.getName())){
            outState.putSerializable("cleans",cleans);
            outState.putSerializable("sussces",sussces);
            outState.putSerializable("faileds",faileds);
            outState.putInt("totalFirdns",totalFirdns);
        }

        super.onSaveInstanceState(outState);

    }

    @Override
    protected void onResume() {
        super.onResume();
        if(!WeiXinCacheUtil.getInfo().isLogin() && contentView.getVisibility()==View.VISIBLE){
            WeiXinLoginActivity.openWeiXingLoginUI(getApplication());
        }
    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
    /**
     * 创建旋转动画
     */
    private RotateAnimation createRotateAnimation() {
        RotateAnimation animation = new RotateAnimation(360, -360, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        //动画执行时间
        animation.setDuration(5000);
        animation.setInterpolator(new LinearInterpolator());
        //动画重复次数-1表示不停重复
        animation.setRepeatCount(-1);
        return  animation;
    }
    /**
     * 创建旋转动画
     */
    private RotateAnimation animationRotateAnimation() {
        RotateAnimation animation = new RotateAnimation(0, -360, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        //动画执行时间
        animation.setInterpolator(new LinearInterpolator());
        animation.setDuration(2000);
        //动画重复次数-1表示不停重复
        animation.setRepeatCount(-1);
        return  animation;


    }
    public static String secToTime(int time) {
        String timeStr = null;
        int hour = 0;
        int minute = 0;
        int second = 0;
        if (time <= 0)
            return "00:00";
        else {
            minute = time / 60;
            if (minute < 60) {
                second = time % 60;
                timeStr = unitFormat(minute) + ":" + unitFormat(second);
            } else {
                hour = minute / 60;
                if (hour > 99)
                    return "99:59:59";
                minute = minute % 60;
                second = time - hour * 3600 - minute * 60;
                timeStr = unitFormat(hour) + ":" + unitFormat(minute) + ":" + unitFormat(second);
            }
        }
        return timeStr;
    }
    public static String unitFormat(int i) {
        String retStr = null;
        if (i >= 0 && i < 10)
            retStr = "0" + Integer.toString(i);
        else
            retStr = "" + i;
        return retStr;
    }

}
